<template>
  <div class="login-page">
    <!-- 顶部登录 -->
    <van-nav-bar title="登录" />

    <!-- 登录表单 -->
    <div class="loginForm">
      <van-form @submit="onSubmit">
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[
            { required: true, message: '请填写用户名' },
            { pattern: /^\w{5,}$/, message: '用户名至少包含5个字符' }
          ]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[
            { required: true, message: '请填写密码' },
            { pattern: /^\w{6,}$/, message: '密码至少包含6个字符' }
          ]"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit">提交</van-button>
        </div>
        <div style="margin: 16px">
          <van-button round block type="info" native-type="reset">重置</van-button>
        </div>
      </van-form>
    </div>

    <!-- 注册导航链接 -->
    <router-link to="/register" class="link">没有账户? 去注册</router-link>
  </div>
</template>

<script>
// 导入 vant 的提示
import { Toast } from 'vant'
// 导入封装的登录的 axios 请求
import { loginRequest } from '@/api/user'
// 导入封装的本地存储
import { setToken } from '@/utils/storage'

export default {
  name: 'login-page',
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async onSubmit(values) {
      // 发起登录请求
      const loginRequestResult = await loginRequest(values)
      // 本地存储 token
      setToken(loginRequestResult.data.token)
      Toast.success('登录成功, 欢迎使用')
      this.$router.push('/')
    }
  }
}
</script>

<style lang="less" scoped>
.loginForm {
  margin-top: 50px;
}

.link {
  color: #069;
  font-size: 12px;
  padding-right: 20px;
  float: right;
}
</style>
